package account

import (
	"NovelBook/dao"
	"NovelBook/models/db_models"
	"NovelBook/models/res"
	"errors"
	"log"
	"strings"
)

func Register(Info res.RegisterInfo, userType UserType) error {

	// 处理验证码
	// 从Redis获取 <email, captcha>
	// 对比：Info.Captcha 与 Redis中的
	captcha, err := GetCaptcha(Info.User.Email)
	if err != nil {
		log.Println("redis error:", err)
		return err
	}
	if captcha != Info.Captcha || err != nil {
		return errors.New("captcha error")
	}

	switch userType {
	case SUPERUSER:
		superuser := db_models.Superuser{Info: Info.User}
		err = dao.GetDb().Create(&superuser).Error
	case MANAGER:
		manger := db_models.Manager{Info: Info.User}
		err = dao.GetDb().Create(&manger).Error
	case WORKER:
		worker := db_models.Worker{Info: Info.User}
		err = dao.GetDb().Create(&worker).Error
		// 为实现 worker 可以借书，在 Borrower 中加入一个完全相同的账号
		borrower := db_models.Borrower{Info: Info.User}
		err = dao.GetDb().Create(&borrower).Error
	case BORROWER:
		borrower := db_models.Borrower{Info: Info.User}
		err = dao.GetDb().Create(&borrower).Error
	}

	if err != nil {
		log.Println(err)
		split := strings.Split(err.Error(), " ")
		if split[1] == "1062" {
			return errors.New("ACCOUNT EXIST")
		}
		return errors.New("database insert error")
	}

	return nil
}
